import { getSongLyric } from '../../api/index'

export default class Song {
  constructor({ id, songMid, singer, name, album, duration, image, url }) {
    this.id = id
    // this.songMid = songMid
    this.singer = singer
    this.name = name
    this.album = album
    this.duration = duration
    this.image = image
    // this.url = url
  }

  getLyric() {
    if (this.lyric) {
      return Promise.resolve(this.lyric)
    }
    return new Promise((resolve, reject) => {
      getSongLyric({ id: this.id }).then(res => {
        if (res.status === 200) {
          this.lyric = res.data.lrc.lyric
          resolve(this.lyric)
        } else {
          reject(new Error('no lyric'))
        }
      })
    })
  }
}

// 这是一个工厂方法, 不直接调用new, 用一个方法返回一个实例
export function createSong(musicData) {
  return new Song({
    id: musicData.id,
    // singer: filterSinger(musicData.ar),
    singer: musicData.ar ? filterSinger(musicData.ar) : filterSinger(musicData.artists),
    name: musicData.name,
    // album: musicData.al.name,
    album: musicData.al ? musicData.al.name : musicData.album.name,
    // image: musicData.al.picUrl || musicData.album.artist.img1v1Url,
    image: musicData.al ? musicData.al.picUrl : musicData.album.artist.img1v1Url,
    // duration: musicData.dt / 1000
    duration: musicData.dt ? musicData.dt / 1000 : musicData.duration / 1000
  })
}

function filterSinger(singer) {
  const ret = []
  if (!singer) {
    return ''
  }
  singer.forEach(s => {
    ret.push(s.name)
  })
  return ret.join(' / ')
}